<template>
  <div>
    <el-form :disabled="type == 'view'" :model="form" ref="ruleForm" label-width="125px" :label-position="type == 'view' ? 'right' : 'top'">
      <div class="table-title-wrap justify-end" v-if="type !== 'view'">
        <el-button icon="el-icon-circle-plus-outline" @click="handleAdd" type="text">新增</el-button>
      </div>
      <div class="card-wrap flex-column justify-end card-padding" v-for="(ruleForm, index) in form.infoVo" :key="index" style="margin-bottom: 20px; border-radius: 8px; position: relative">
        <div class="card-title-wrap">
          <span>序号{{ index + 1 }}</span>
          <span></span>
        </div>
        <i class="el-icon-close" v-if="type !== 'view'" circle @click="reduction(ruleForm, index)" style="cursor: pointer; position: absolute; right: 0; top: 0; font-size: 20px; color: #409eff"></i>
        <div class="box">
          <el-descriptions title="车辆信息"> </el-descriptions>
          <el-row>
            <el-col :span="8">
              <el-form-item label="车辆性质:" :prop="`infoVo.${index}.carNature`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入车辆性质' }">
                <el-select v-if="type !== 'view'" disabled v-model="ruleForm.carNature" clearable :style="{ width: type == 'view' ? '69%' : '78%' }">
                  <template v-for="dict in dict.type.car_nature">
                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                  </template>
                </el-select>
                <dict-tag v-if="type == 'view'" :options="dict.type.car_nature" :value="ruleForm.carNature" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆品牌:" style="width: 78%" :prop="`infoVo.${index}.carBrandName`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入车辆品牌' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carBrandName" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carBrandName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车型:" style="width: 78%" :prop="`infoVo.${index}.carModelName`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入车型' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carModelName" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carModelName }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="车系:" style="width: 78%" :prop="`infoVo.${index}.carSeriesName`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入车系' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carSeriesName" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carSeriesName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="座位数:" style="width: 78%" :prop="`infoVo.${index}.carSeating`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入座位数' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carSeating" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carSeating }}</span>
              </el-form-item>
            </el-col>
            <!-- :prop="`infoVo.${index}.carCc`" :rules="{required: true,trigger: 'blur', message: '请输入排量' }" -->
            <el-col :span="8">
              <el-form-item label="排量:" style="width: 78%" :prop="`infoVo.${index}.carCc`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入排量' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carCc" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carCc }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="排放标准:" style="width: 78%" :prop="`infoVo.${index}.carStandard`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入环保标准' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carStandard" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carStandard }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="变速类型:" style="width: 78%" :prop="`infoVo.${index}.carTransmission`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入变速器' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carTransmission" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carTransmission }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="燃油类型:" style="width: 78%" :prop="`infoVo.${index}.carPowerTypeStr`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入燃油类型' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carPowerTypeStr" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carPowerTypeStr }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="年行驶公里数:" style="width: 78%">
                <el-input v-if="type !== 'view'" v-model="ruleForm.travelKilometer" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.travelKilometer }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="内饰颜色:" style="width: 78%" :prop="`infoVo.${index}.carInteriorColor`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入内饰颜色' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carInteriorColor" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carInteriorColor }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外观颜色:" style="width: 78%" :prop="`infoVo.${index}.appearanceColor`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入外观颜色' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.appearanceColor" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.appearanceColor }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="新车/旧车:" :prop="`infoVo.${index}.carFlag`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择' }">
                <!-- <el-select v-if="type !=='view'" v-model="ruleForm.carFlag" :style="{width: type=='view'?'69%':'78%'}">
                  <template v-for="dict in dict.type.new_or_old_cars">
                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                  </template>
                </el-select>
                <dict-tag v-if="type =='view'" :options="dict.type.new_or_old_cars" :value="ruleForm.carFlag" /> -->
                <el-input v-if="type !== 'view'" v-model="ruleForm.carFlag" disabled :style="{ width: type == 'view' ? '69%' : '78%' }"></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carFlag }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="支付时间:" style="width: 78%">
                <el-input v-if="type !== 'view'" v-model="ruleForm.payTime" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.payTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="付款频次:" style="width: 78%">
                <el-input v-if="type !== 'view'" v-model="ruleForm.payFrequency" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.payFrequency }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="保证金:" style="width: 78%">
                <el-input v-if="type !== 'view'" v-model="ruleForm.margin" disabled></el-input>
                <span v-if="type == 'view'">{{ format_thousand(ruleForm.margin) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租期:" style="width: 78%">
                <el-input v-if="type !== 'view'" v-model="ruleForm.lease" disabled></el-input>
                <span v-if="type == 'view'">{{ ruleForm.lease }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="首付款:" style="width: 78%">
                <el-input v-if="type !== 'view'" v-model="ruleForm.firstPayMoney" disabled></el-input>
                <span v-if="type == 'view'">{{ format_thousand(ruleForm.firstPayMoney) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="每期租金:" style="width: 78%">
                <el-input v-if="type !== 'view'" v-model="ruleForm.monthRentPayment" disabled></el-input>
                <span v-if="type == 'view'">{{ format_thousand(ruleForm.monthRentPayment) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆运营:" style="width: 78%" :prop="`infoVo.${index}.carOperations`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入车辆运营' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carOperations" disabled clearable maxlength="30"></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carOperations }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆归属:" style="width: 78%" :prop="`infoVo.${index}.carAscription`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择车辆归属' }">
                <!-- <el-select filterable maxlength="30" @change="changeCarAsc(ruleForm.carAscriptionId,index)" v-model="ruleForm.carAscriptionId" clearable :style="{width: type=='view'?'69%':'78%'}">
                  <template v-for="dict in carAscriptionList">
                    <el-option :label="dict.deptName" :value="dict.deptId" :key="dict.deptId"></el-option>
                  </template>
                </el-select> -->
                <el-input v-if="type !== 'view'" v-model="ruleForm.carAscription" disabled clearable maxlength="30"></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carAscription }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="车辆产权:" style="width: 78%" :prop="`infoVo.${index}.carProperty`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入车辆产权' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.carProperty" disabled clearable maxlength="30"></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carProperty }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车辆大区:" style="width: 78%">
                <!-- <el-select filterable maxlength="30" @change="changeCarReg(ruleForm.carRegionId,index)" v-model="ruleForm.carRegionId" clearable :style="{width: type=='view'?'69%':'78%'}">
                  <template v-for="dict in areaList">
                    <el-option :label="dict.areaName" :value="dict.areaId" :key="dict.areaId"></el-option>
                  </template>
                </el-select> -->
                <el-input v-if="type !== 'view'" v-model="ruleForm.carRegion" disabled clearable maxlength="30"></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carRegion }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="采购台数:" style="width: 78%" :prop="`infoVo.${index}.carNumber`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入采购台数' }">
                <el-input v-if="type !== 'view'" disabled v-model="ruleForm.carNumber" clearable @input="changeInput(ruleForm)"></el-input>
                <span v-if="type == 'view'">{{ ruleForm.carNumber }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="上牌来源:" :prop="`infoVo.${index}.carRegistrationSource`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择上牌来源' }">
                <el-select v-if="type !== 'view'" filterable maxlength="30" v-model="ruleForm.carRegistrationSource" clearable :style="{ width: type == 'view' ? '69%' : '78%' }">
                  <template v-for="dict in dict.type.out_rent_source">
                    <el-option :label="dict.label" :value="Number(dict.value)" :key="Number(dict.value)"></el-option>
                  </template>
                </el-select>
                <dict-tag v-if="type == 'view'" :options="dict.type.out_rent_source" :value="ruleForm.carRegistrationSource" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="首年保险:" :prop="`infoVo.${index}.carInsuranceSource`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择保险' }">
                <el-select @change="changeBx(ruleForm.carInsuranceSource, index)" v-if="type !== 'view'" filterable maxlength="30" v-model="ruleForm.carInsuranceSource" clearable :style="{ width: type == 'view' ? '69%' : '78%' }">
                  <template v-for="dict in dict.type.out_insurance_source">
                    <el-option :label="dict.label" :value="Number(dict.value)" :key="Number(dict.value)"></el-option>
                  </template>
                </el-select>
                <dict-tag v-if="type == 'view'" :options="dict.type.out_insurance_source" :value="ruleForm.carInsuranceSource" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="加装来源:" :prop="`infoVo.${index}.carEquipSource`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择加装来源' }">
                <el-select v-if="type !== 'view'" filterable maxlength="30" v-model="ruleForm.carEquipSource" clearable :style="{ width: type == 'view' ? '69%' : '78%' }">
                  <template v-for="dict in dict.type.out_rent_source">
                    <el-option :label="dict.label" :value="Number(dict.value)" :key="Number(dict.value)"></el-option>
                  </template>
                </el-select>
                <dict-tag v-if="type == 'view'" :options="dict.type.out_rent_source" :value="ruleForm.carEquipSource" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="GPS来源:" :prop="`infoVo.${index}.carGpsSource`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择GPS来源' }">
                <el-select v-if="type !== 'view'" filterable maxlength="30" v-model="ruleForm.carGpsSource" clearable :style="{ width: type == 'view' ? '69%' : '78%' }">
                  <template v-for="dict in dict.type.out_rent_source">
                    <el-option :label="dict.label" :value="Number(dict.value)" :key="Number(dict.value)"></el-option>
                  </template>
                </el-select>
                <dict-tag v-if="type == 'view'" :options="dict.type.out_rent_source" :value="ruleForm.carGpsSource.toString()" />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="购置税来源:" :prop="`infoVo.${index}.carPurchaseSource`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择购置税来源' }">
                <el-select v-if="type !== 'view'" filterable v-model="ruleForm.carPurchaseSource" clearable :style="{ width: type == 'view' ? '69%' : '78%' }">
                  <template v-for="dict in dict.type.out_rent_source">
                    <el-option :label="dict.label" :value="Number(dict.value)" :key="Number(dict.value)"></el-option>
                  </template>
                </el-select>
                <dict-tag v-if="type == 'view'" :options="dict.type.out_rent_source" :value="ruleForm.carPurchaseSource" />
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="ruleForm.carInsuranceSource == 0">
              <el-form-item label="投保渠道:" :prop="`infoVo.${index}.insureChannel`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择投保渠道' }">
                <el-select v-if="type !== 'view'" filterable v-model="ruleForm.insureChannel" clearable :style="{ width: type == 'view' ? '69%' : '78%' }">
                  <template v-for="dict in dict.type.out_rent_insure_channel">
                    <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                  </template>
                </el-select>
                <dict-tag v-if="type == 'view'" :options="dict.type.out_rent_insure_channel" :value="ruleForm.insureChannel" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div class="box">
          <el-descriptions title="外部转租赁供应商信息"> </el-descriptions>
          <el-row>
            <el-col :span="8">
              <el-form-item label="供应商名称:" :prop="`infoVo.${index}.supplierId`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择供应商名称' }">
                <el-select v-if="type !== 'view'" filterable maxlength="30" v-model="ruleForm.supplierId" :style="{ width: type == 'view' ? '69%' : '78%' }" @change="changeSup(ruleForm.supplierId, index)">
                  <template v-for="dict in supplierList">
                    <el-option :label="dict.supplierName" :value="dict.supplierId" :key="dict.supplierId"></el-option>
                  </template>
                </el-select>
                <!-- <dict-tag v-if="type =='view'" :options="supplierList" :value="ruleForm.supplierId.toString()" /> -->
                <span v-if="type == 'view'">{{ ruleForm.supplier }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户名称:" :prop="`infoVo.${index}.account`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入账户' }">
                <el-select v-if="type !== 'view'" filterable maxlength="30" @change="changeAcc(ruleForm.accountList, index)" v-model="ruleForm.account" :style="{ width: type == 'view' ? '69%' : '78%' }">
                  <template v-for="dict in ruleForm.accountList">
                    <el-option :label="dict.bankName" :value="dict.bankName" :key="dict.bankName"></el-option>
                  </template>
                </el-select>
                <span v-if="type == 'view'">{{ ruleForm.account }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="留购价:" style="width: 78%" :prop="`infoVo.${index}.purchasePrice`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入留购价' }">
                <el-input v-if="type !== 'view'" @input="ruleForm.purchasePrice = ruleForm.purchasePrice.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')" v-model="ruleForm.purchasePrice" clearable></el-input>
                <span v-if="type == 'view'">{{ format_thousand(ruleForm.purchasePrice) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="首付款:" style="width: 78%" :prop="`infoVo.${index}.firstPayment`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入首付款' }">
                <el-input v-if="type !== 'view'" @input="ruleForm.firstPayment = ruleForm.firstPayment.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')" v-model="ruleForm.firstPayment" clearable></el-input>
                <span v-if="type == 'view'">{{ format_thousand(ruleForm.firstPayment) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="首付款付款时间:" :prop="`infoVo.${index}.firstPaymentTime`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择首付款付款时间' }">
                <el-date-picker value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-if="type !== 'view'" v-model="ruleForm.firstPaymentTime" type="date" placeholder="选择日期" :style="{ width: type == 'view' ? '69%' : '78%' }">
                </el-date-picker>
                <span v-if="type == 'view'">{{ ruleForm.firstPaymentTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="租期:" style="width: 78%" :prop="`infoVo.${index}.rentStage`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入租期' }">
                <el-input @change="changeTimeZq(index)" v-if="type !== 'view'" v-model="ruleForm.rentStage" clearable @input="ruleForm.rentStage = ruleForm.rentStage.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"></el-input>
                <span v-if="type == 'view'">{{ ruleForm.rentStage }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="保证金:" style="width: 78%" :prop="`infoVo.${index}.ensureMoney`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入保证金' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.ensureMoney" clearable @input="ruleForm.ensureMoney = ruleForm.ensureMoney.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"></el-input>
                <span v-if="type == 'view'">{{ format_thousand(ruleForm.ensureMoney) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="保证金付款时间:" :prop="`infoVo.${index}.ensurePaymentTime`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择保证金付款时间' }">
                <el-date-picker value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-if="type !== 'view'" v-model="ruleForm.ensurePaymentTime" type="date" placeholder="选择日期" :style="{ width: type == 'view' ? '69%' : '78%' }">
                </el-date-picker>
                <span v-if="type == 'view'">{{ ruleForm.ensurePaymentTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="月租金:" style="width: 78%" :prop="`infoVo.${index}.monthRentMoney`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入月租金' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.monthRentMoney" clearable @input="ruleForm.monthRentMoney = ruleForm.monthRentMoney.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"></el-input>
                <span v-if="type == 'view'">{{ format_thousand(ruleForm.monthRentMoney) }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" style="position: relative">
              <el-form-item label="月租金付款时间" :prop="`infoVo.${index}.monthPaymentTime`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择月租金付款时间' }">
                <span v-if="type !== 'view'" style="color: red; position: absolute; left: 110px; top: -43px">(每期租金时间):</span>
                <el-date-picker
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  @change="changeTime(index)"
                  v-if="type !== 'view'"
                  v-model="ruleForm.monthPaymentTime"
                  type="date"
                  placeholder="选择日期"
                  :style="{ width: type == 'view' ? '69%' : '78%' }"
                >
                </el-date-picker>
                <span v-if="type == 'view'" style="color: red; position: absolute; left: -10px; top: 0">(每期租金时间):</span>
                <span v-if="type == 'view'" style="margin-left: 90px">{{ ruleForm.monthPaymentTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="期满租金:" style="width: 78%" :prop="`infoVo.${index}.expireRentMoney`" :rules="type == 'view' ? [] : { required: true, trigger: 'blur', message: '请输入期满租金' }">
                <el-input v-if="type !== 'view'" v-model="ruleForm.expireRentMoney" clearable @input="ruleForm.expireRentMoney = ruleForm.expireRentMoney.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"></el-input>
                <span v-if="type == 'view'">{{ format_thousand(ruleForm.expireRentMoney) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="期满租金付款时间:" :prop="`infoVo.${index}.expirePaymentTime`" :rules="type == 'view' ? [] : { required: true, trigger: 'change', message: '请选择期满租金付款时间' }">
                <el-date-picker value-format="yyyy-MM-dd" format="yyyy-MM-dd" v-if="type !== 'view'" v-model="ruleForm.expirePaymentTime" type="date" placeholder="选择日期" :style="{ width: type == 'view' ? '69%' : '78%' }">
                </el-date-picker>
                <span v-if="type == 'view'">{{ ruleForm.expirePaymentTime }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-form>

    <!-- 弹窗添加车型 -->
    <el-dialog :title="title" :visible.sync="open" width="60%">
      <div style="width: 100%; margin: 0 auto">
        <el-table :loading="loading" max-height="400" ref="table" :data="dataList" border @selection-change="handleSelectionChange">
          <!-- :selectable="selectable" -->
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="采购台数" align="center" width="100">
            <template slot-scope="scope">
              <!-- :disabled='scope.row.carNumber == 0'  -->
              <el-input placeholder="请输入" v-model="scope.row.carNumber" @input="changeNumber(scope)"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="需采购台数" align="center" prop="needProcureNumber" />
          <el-table-column label="车系" align="center" prop="carSeriesName" />
          <el-table-column label="车型" align="center" prop="carModelName" min-width="150px" show-overflow-tooltip />
          <el-table-column label="品牌" align="center" prop="carBrandName" />
          <el-table-column label="座位数" align="center" prop="carSeating" />
          <el-table-column label="排量" align="center" prop="carCc" />
          <el-table-column label="燃油类型" align="center" prop="carPowerTypeStr" />
          <el-table-column label="变速器" align="center" prop="carTransmission" />
          <el-table-column label="环保标准" align="center" prop="carStandard" />
          <el-table-column label="内饰颜色" align="center" prop="carInteriorColor" />
          <el-table-column label="外观颜色" align="center" prop="appearanceColor" />
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="addForm">添 加</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listDept, areaList } from '@/api/system/dept'
import { getInsuranceSelectList } from '@/api/cwgd/insuranceSelect'
import { getCarInfo } from '@/api/purchaseManage/sublease'
import { supplierDetail } from '@/api/memberManage/vendorList'
export default {
  name: 'vehicleInformation',
  dicts: ['car_nature', 'out_rent_insure_channel', 'vehicle_category', 'new_or_old_cars', 'out_insurance_source', 'out_rent_source', 'out_rent_source'],
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: '',
    },
  },
  watch: {
    'value.orderId': {
      handler(val) {
        this.getCarInfo(val)
      },
      deep: true,
    },
  },
  computed: {
    form: {
      get() {
        let that = this
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key)
          },
          set(target, key, value) {
            that.$emit('input', { ...target, [key]: value })
            return true
          },
        })
        return proxy
      },
    },
    type() {
      let status
      switch (this.state) {
        case 'write':
          status = 'edit'
          break
        case 1:
          status = 'view'
        case 'disabled':
          status = 'view'
          break
        case 'readonly':
          status = 'view'
          break
        case 'view':
          status = 'view'
          break
        case 'edit':
          status = 'edit'
          break
      }
      return status
    },
  },
  data() {
    return {
      supplierList: [],
      carAscriptionList: [],
      multipleSelection: [],
      dataList: [],
      loading: false,
      title: '新增',
      open: false,
      areaList: [],
      listIds: [],
      sourceList: [
        {
          label: '近多出行',
          value: 0,
        },
        {
          label: '外部转租赁公司负责',
          value: 1,
        },
      ],
      insuranceList: [
        {
          label: '我司担保',
          value: 0,
        },
        {
          label: '外部转租赁公司负责',
          value: 1,
        },
      ],
      result: [],
    }
  },
  mounted() {
    // this.getCompanyList();
    // this.getAreaList();
    this.getSupplierList()
  },
  methods: {
    addOneMonth(dateString, month) {
      const date = new Date(dateString)
      date.setMonth(date.getMonth() + Number(month))
      date.setDate(date.getDate())
      return date.toISOString().split('T')[0] // 返回YYYY-MM-DD格式的日期字符串
    },
    changeTime(index) {
      if (this.form.infoVo[index].rentStage) {
        if (this.form.infoVo[index].monthPaymentTime) {
          let end = this.addOneMonth(this.form.infoVo[index].monthPaymentTime, Number(this.form.infoVo[index].rentStage))
          this.$set(this.form.infoVo[index], 'expirePaymentTime', end)
        } else {
          this.$set(this.form.infoVo[index], 'expirePaymentTime', null)
        }
      }
    },
    changeTimeZq(index) {
      if (this.form.infoVo[index].monthPaymentTime) {
        let end = this.addOneMonth(this.form.infoVo[index].monthPaymentTime, Number(this.form.infoVo[index].rentStage))
        this.$set(this.form.infoVo[index], 'expirePaymentTime', end)
      } else {
        this.$set(this.form.infoVo[index], 'expirePaymentTime', null)
      }
    },
    changeBx(type, i) {
      console.log(type, i)
      if (type == 1) {
        this.$set(this.form.infoVo[i], 'insureChannel', null)
      }
    },
    // changeCarAsc(id, i) {
    //   console.log(id, i);
    //   let carAscription = this.carAscriptionList
    //     .map((v) => {
    //       if (v.deptId == id) {
    //         return v.deptName;
    //       }
    //     })
    //     .filter((i) => i)[0];
    //   console.log(carAscription);
    //   this.$set(this.form.infoVo[i], "carAscription", carAscription);
    // },
    // changeCarReg(id, i) {
    //   console.log(id, i);
    //   let carRegion = this.areaList
    //     .map((v) => {
    //       if (v.areaId == id) {
    //         return v.areaName;
    //       }
    //     })
    //     .filter((i) => i)[0];
    //   this.$set(this.form.infoVo[i], "carRegion", carRegion);
    // },
    changeAcc(l, i) {
      console.log(l, i)
      let accountNumber = l[i]?.accountNumber
      let bankCode = l[i]?.bankCode
      this.$set(this.form.infoVo[i], 'accountNumber', accountNumber)
      this.$set(this.form.infoVo[i], 'bankCode', bankCode)
    },
    changeSup(id, i) {
      let supplier = this.supplierList
        .map((v) => {
          if (v.supplierId == id) {
            return v.supplierName
          }
        })
        .filter((i) => i)[0]
      this.$set(this.form.infoVo[i], 'supplier', supplier)
      this.$set(this.form.infoVo[i], 'account', '')
      supplierDetail(this.form.infoVo[i].supplierId).then((res) => {
        let arr = res.data.accounts
        console.log(arr, 'arr')
        this.$set(this.form.infoVo[i], 'accountList', arr)
      })
    },
    changeInput(val) {
      let number = this.dataList
        .map((item) => {
          if (item.carModelId == val.carModelId) {
            return Number(item.needProcureNumber) - Number(item.carNumber)
          }
        })
        .filter((i) => i)[0]
      if (Number(val.carNumber) >= number) {
        this.$message.error(`采购数量不能大于${number},请重新填写`)
        val.carNumber = ''
      }
    },
    changeNumber(scope) {
      if (Number(scope.row.carNumber) == 0) {
        this.$message.error('采购数量不能为0')
        scope.row.carNumber = ''
      } else {
        if (Number(scope.row.carNumber) > Number(scope.row.needProcureNumber)) {
          this.$message.error('采购数量不能大于需采购数量')
          scope.row.carNumber = ''
        }
      }
    },
    selectable(row) {
      if (row.carNumber == 0) {
        return false
      } else {
        return true
      }
    },
    async getCarInfo(val) {
      let data = {
        orderId: val,
        id: this.$route.query.id,
      }
      try {
        let res = await getCarInfo(data)
        this.dataList = res.data.map((v) => {
          return {
            ...v,
            carNumber: v.needProcureNumber,
            number: 0,
            alreadyDisabled: false,
          }
        })
      } catch (error) {}
    },
    getSupplierList() {
      let params = {
        businessTypeCode: '6',
        availableStatus: '0',
      }
      getInsuranceSelectList(params).then((res) => {
        this.supplierList = res.data
        console.log(this.supplierList, 'supplierList')
      })
    },
    /** 获取区域列表*/
    getAreaList() {
      areaList().then((res) => {
        this.areaList = res.data
      })
    },
    //获取所属公司列表
    getCompanyList() {
      listDept({
        deptType: '2', //组织类型（1部门 2公司）
      }).then((res) => {
        this.carAscriptionList = res.data.map((v) => {
          return {
            ...v,
            deptId: v.deptId.toString(),
          }
        })
      })
    },
    handleEffect() {
      let bool
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          bool = true
        } else {
          this.error()
          bool = false
        }
      })
      return bool
    },
    error() {
      this.$nextTick(() => {
        const el = document.querySelectorAll('.el-form-item__error')[0]
        el && el.scrollIntoView({ block: 'center', behavior: 'smooth' })
      })
    },
    // 全选字段
    handleSelectionChange(val) {
      console.log(val, 'val')
      this.multipleSelection = val
    },
    deduplicateAllOrderCarIds(arr) {
      const allIds = arr.flatMap((item) => item.allOrderCarIds?.split(','))
      const uniqueIds = [...new Set(allIds)]
      const combinedIds = uniqueIds.join(',')
      return [{ allOrderCarIds: combinedIds }]
    },
    handleAdd() {
      console.log(this.$route.query.type, 'this.$route.query.type', this.dataList)
      this.multipleSelection = []
      this.open = true
      // ---------修改后的逻辑---------\
      if (this.$route.query.type == 'edit') {
        this.dataList.forEach((v) => {
          this.form.infoVo.forEach((j) => {
            let arr1 = v.allOrderCarIds.split(',')
            let arr2 = j.orderCarId.split(',')
            let isAllIncluded = arr2.every((element) => arr1.includes(element))
            if (isAllIncluded) {
              j.allOrderCarIds = v.allOrderCarIds
            }
          })
        })
      }
      this.listIds = this.deduplicateAllOrderCarIds(this.form.infoVo)
      console.log(this.listIds)
      console.log(this.listIds, 'listIds')
      let list = this.form.infoVo?.map((v) => {
        return {
          orderCarId: v.orderCarId,
          carNumber: Number(v.carNumber),
        }
      })
      this.result = this.listIds.reduce((acc, obj1) => {
        let idsArr1 = obj1.allOrderCarIds
        let matchedObjects = list.filter((item) => idsArr1.includes(item.orderCarId))
        if (matchedObjects.length > 0) {
          let orderCarId = matchedObjects.map((item) => item.orderCarId)
          let carNumber = matchedObjects.reduce((total, item) => total + item.carNumber, 0)
          acc.push({ orderCarId: orderCarId.join(','), carNumber: carNumber })
        }
        return acc
      }, [])
      console.log(this.result, 'result')
      this.dataList.forEach((v, i) => {
        this.result?.forEach((j, i) => {
          let arr1 = v.allOrderCarIds.split(',')
          let arr2 = j.orderCarId.split(',')
          let isAllIncluded = arr2.every((element) => arr1.includes(element))
          if (isAllIncluded) {
            v.carNumber = Number(v.needProcureNumber) - Number(j.carNumber)
          }
        })
      })
      //-------------修改后的逻辑-----------------

      // ----------修改前的逻辑-------------
      // let list = this.form.infoVo?.map((v) => {
      //   return {
      //     carModelId: v.carModelId,
      //     carNumber: Number(v.carNumber),
      //   };
      // });
      // console.log(list, 'list', this.form.infoVo, 'this.form.infoVo');
      // const result = list.reduce((acc, curr) => {
      //   const foundIndex = acc.findIndex(
      //     (item) => item.carModelId === curr.carModelId
      //   );
      //   if (foundIndex !== -1) {
      //     acc[foundIndex].carNumber += curr.carNumber;
      //   } else {
      //     acc.push({ ...curr });
      //   }
      //   return acc;
      // }, []);
      // this.dataList.forEach((v, i) => {
      //   result.forEach((j, i) => {
      //     if (v.carModelId === j.carModelId) {
      //       v.carNumber = Number(v.needProcureNumber) - Number(j.carNumber);
      //     }
      //   });
      // });
      // ----------修改前的逻辑-------------
    },
    reduction(ruleForm, i) {
      this.form.infoVo.splice(i, 1)
      // -----------修改后--------------
      this.listIds = this.deduplicateAllOrderCarIds(this.form.infoVo)
      let list = this.form.infoVo?.map((v) => {
        return {
          orderCarId: v.orderCarId,
          carNumber: Number(v.carNumber),
        }
      })
      let result = this.listIds.reduce((acc, obj1) => {
        let idsArr1 = obj1.allOrderCarIds
        let matchedObjects = list.filter((item) => idsArr1.includes(item.orderCarId))
        if (matchedObjects.length > 0) {
          let orderCarId = matchedObjects.map((item) => item.orderCarId)
          let carNumber = matchedObjects.reduce((total, item) => total + item.carNumber, 0)
          acc.push({ orderCarId: orderCarId.join(','), carNumber: carNumber })
        }
        return acc
      }, [])
      console.log(result, 'result')
      this.dataList.forEach((v, i) => {
        if (result.length > 0) {
          result.forEach((j, i) => {
            let arr1 = v.allOrderCarIds.split(',')
            let arr2 = j.orderCarId.split(',')
            let isAllIncluded = arr2.every((element) => arr1.includes(element))
            if (isAllIncluded) {
              v.carNumber = Number(v.needProcureNumber) - Number(j.carNumber)
            }
          })
        } else {
          v.carNumber = Number(v.needProcureNumber)
        }
      })
      // -----------修改后--------------

      // -----------修改前--------------
      // let list = this.form.infoVo?.map((v) => {
      //   return {
      //     carModelId: v.carModelId,
      //     carNumber: Number(v.carNumber),
      //   }
      // })
      // const result = list.reduce((acc, curr) => {
      //   const foundIndex = acc.findIndex((item) => item.carModelId === curr.carModelId)
      //   if (foundIndex !== -1) {
      //     acc[foundIndex].carNumber += curr.carNumber
      //   } else {
      //     acc.push({ ...curr })
      //   }
      //   return acc
      // }, [])
      // console.log(list, result)
      // this.dataList.forEach((v, i) => {
      //   if (result.length > 0) {
      //     result.forEach((j, i) => {
      //       if (v.carModelId === j.carModelId) {
      //         v.carNumber = Number(j.carNumber)
      //       }
      //     })
      //   } else {
      //     v.carNumber = Number(v.needProcureNumber)
      //   }
      // })
      // -----------修改前--------------
    },
    cancel() {
      this.open = false
      this.clear()
    },
    clear() {
      this.$nextTick(() => {
        this.$refs.table.clearSelection()
      })
    },
    addForm() {
      console.log(this.form.infoVo, 'this.form.infoVo')
      this.open = false
      this.clear()
      // ----------修改后-----------------
      this.multipleSelection.forEach((v) => {
        if (this.form.infoVo.length > 0) {
          this.result.forEach((j) => {
            let arr1 = v.allOrderCarIds.split(',')
            let arr2 = j.orderCarId.split(',')
            let isAllIncluded = arr2.every((element) => arr1.includes(element))
            console.log(isAllIncluded, ';isAllIncluded', arr2.length, 'arr2.length')
            if (isAllIncluded) {
              let string = v.orderCarIds.split(',').slice(j.carNumber, Number(v.carNumber) + Number(j.carNumber))
              v.orderCarId = string.toString()
            }
          })
        } else {
          let string = v.orderCarIds.split(',').slice(0, Number(v.carNumber))
          v.orderCarId = string.toString()
        }
      })
      // ----------修改后-----------------

      // ---------修改前------------
      // this.multipleSelection.forEach(v => {
      //   let string = v.orderCarIds.split(",").slice(0, Number(v.carNumber))
      //   v.orderCarId = string.toString()
      // })
      // ---------修改前------------
      let obj = JSON.parse(JSON.stringify(this.multipleSelection))
      this.form.infoVo.push(...obj)
    },
  },
}
</script>
<style lang="scss" scoped>
.app-container {
  background-color: #fff;
}
.box {
  width: 100%;

  .title {
    border-left: 3px solid #3278fc;
    padding-left: 5px;
    box-sizing: border-box;
  }

  .content {
    width: 90%;
    margin: 0 auto;
  }
}
.icon_add {
  margin-left: 10px;
  cursor: pointer;
}
</style>
